package view.GUI.adminView.coreData.people.person;

import model.data.interfaces.IFinishable;
import model.data.tableModel.person.Person;
import enums.GUIText;
import enums.Status;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.stage.Stage;
import view.GUI.adminView.coreData.people.EditBox;
import view.GUI.mainView.MainView;


public final class EditPersonView extends PersonView{
	
	private EditBox editbox;	
	
	public EditPersonView(MainView instance) {
		super(true, instance, GUIText.EDITPERSON);
		editbox = new EditBox(valSup, GUIText.PERSON, owner.getPersons());
		
		int columnCounter = 0;
		for(Node n: editbox.getNodes()){
			super.addNode(n, columnCounter++, 0);
			
		}
		
		editbox.getComboBox().getSelectionModel().selectedItemProperty().addListener(new ChangeListener<IFinishable>(){

			@Override
			public void changed(ObservableValue<? extends IFinishable> observable, IFinishable oldValue, IFinishable newValue) {
				gridNewPerson.setPerson((Person) newValue);
				
			}
		});
		try {
			start(new Stage());
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	protected boolean save() {
		// If the Person should be deleted
		if(editbox.isDeleteSelected()){
			IFinishable p = editbox.getComboBox().getSelectionModel().getSelectedItem();
			p.setStatus(Status.INACTIVE);
			p.writeUpdateToDB();
			return true;
		} else{
			Person p = ((Person) editbox.getComboBox().getSelectionModel().getSelectedItem());
			if(gridNewPerson.getPerson() != null){
				Person newPerson = gridNewPerson.getPerson();
				
				p.setPerson(newPerson);
				p.setMail(gridNewPerson.getMail());
				p.setRoom(Integer.valueOf(gridNewPerson.getRoom()));
				p.setLastName(newPerson.getLastName());
				p.setFirstName(newPerson.getFirstName());
				p.writeUpdateToDB();
				return true;
			}
			return true;
		}
	}

}
